package com.linghang.wusthelper.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @uthor Fegert
 * @Date 2020/3/1 14:42
 * 主数据源配置（武科大助手 数据库）
 */

@Configuration//标记 此类为配置类
@EnableConfigurationProperties
@MapperScan(basePackages = "com.linghang.wusthelper.dao.primary", sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class PrimaryDBConfig {
    /**
     * spring 容器初始化时添加主数据源的DataSource对象Bean
     *
     * @return DataSource对象
     */
    @Bean(name = "primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")//application.yml中读取主数据源信息
    @Primary
    public DataSource primaryDataSource() {
       DataSource result= DataSourceBuilder.create().build();
        return result;
    }

    /**
     * 配置Session工厂
     *
     * @param dataSource
     * @return SqlSessionFactory对象
     * @throws Exception
     */
    @Bean(name = "primarySqlSessionFactory")
    @Primary
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().
                getResources("classpath*:/mapper/primary/*.xml"));
        return bean.getObject();
    }

    @Bean("primaryDataSourceTransactionManager")
    @Primary
    public DataSourceTransactionManager primaryDataSourceTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }



    /**
     * 模板
     * @param sqlSessionFactory
     * @return
     */
    @Bean(name = "primarySqlSessionTemplate")
    @Primary
    public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
